<template>
<!-- 物资类别权限设置 -->
    <div class="base-page" v-if="isShow">
        <div class="left">
            <select-org @select="onSelectOrg" />
        </div>
        <div class="right">
            <div class="e-table">
                <div class="top">
                    <div class="left">
                        <div class="left-btn">
                            <el-button size="mini"  @click="GoJurisdiction(formData)">分配权限</el-button>
                            <el-button type="danger" size="mini" @click="ctDelete">删除</el-button>
                        </div>
                    </div>
                    <!-- <div class="search_box">
                        <el-input class="ipt" type="text"
                            placeholder="输入搜索关键字"
                            v-model="searchKey"
                            @select="onSearch"
                            @change="onSearch"
                        ><img src="@/assets/search.png" slot="suffix" @click="onSearch" /></el-input>
                        <div class="adverse">
                            <el-button type="primary" @click="onAdvanceSearch">高级搜索</el-button>
                        </div>
                    </div> -->
                </div>
            </div>
            <div  :style="{width: rightTableWidth}">
                <el-table
                    class="table"
                    :height="rightTableHeight"
                    :data="tableData"
                    border
                    :cell-class-name="cellClsNm"
                    highlight-current-row
                    @current-change="handleCurrentChange"
                    @selection-change="planTableSelect"
                >
                     <el-table-column type="selection" width="55" >
                     </el-table-column>
                        <el-table-column prop="orgName" label="所属机构" min-width="200" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="state" label="数据权限" min-width="100" >
                            <template>
                                {{'本机构及其下级'}}
                            </template>
                        </el-table-column>

                </el-table>
            </div>
            <Pagination
                :total="paginationInfo.total"
                :pageSize.sync="paginationInfo.pageSize"
                :currentPage.sync="paginationInfo.currentPage"
                @currentChange="getTableData"
                @sizeChange="getTableData"
            />
        </div>

    </div>
    <!-- 分配权限页面 -->
     <div class="base-page " v-else>
            <div class="right" >
                <div class="e-form" style="padding: 0 10px 10px;">
                    <span>当前机构:{{orgName}}</span>
                     <el-table
                        :data="goodsDataList"
                        ref="multipleTable"
                        border
                        style="width: 100%"
                        :cell-class-name="cellClsNm"
                        :header-cell-style="{ textAlign: 'center' }"
                        :cell-style="{ textAlign: 'center' }"
                        :tree-props="{
                        children: 'children',
                        hasChildren: 'hasChildren',
                        }"
                        row-key="billId"
                        :max-height="$store.state.tableHeight"
                    >
                     <el-table-column
                        label="操作"
                        width="300px"
                        align="left"
                        type=""
                        >
                        <template slot-scope="{ row}">
                          <el-button type="primary" size="mini" @click="checkedAll(row)">全选</el-button>
                          <el-button type="danger" size="mini" @click="cancelCheckedAll(row)">取消全选</el-button>
                        </template>
                        </el-table-column>
                        <el-table-column
                            prop="className"
                            label="类别名称"
                            min-width="200"
                            align="left"
                            >
                            </el-table-column>
                            <el-table-column
                            min-width="200"
                            align="left"
                            >
                                <template slot="header">
                                    <span>用例</span>
                                    <i slot="suffix">
                                            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange" >全选</el-checkbox>
                                    </i>
                                </template >
                                <template slot-scope="{ row }">
                                    <div v-if="row.checkedCities">
                                        <el-checkbox-group v-model="row.checkedCities" >
                                            <el-checkbox v-for="city in cities"  :label="city" :key="city" @change="handleCheckedCitiesChange(city,row,$event)">{{city}}</el-checkbox>
                                        </el-checkbox-group>
                                    </div>
                                </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="footer">
                    <div class="right-btn">
                        <el-button type="primary" size="mini"
                        @click="onSave"
                        >保存</el-button>
                        <el-button type="default" size="mini"
                        @click="onCancel"
                        >取消</el-button>
                    </div>
                </div>
            </div>
        </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import SelectOrg from '@/pages/materialsmanagement/sendReceiveLock/selectOrgName'
import Pagination from '@/components/pagination/pagination'
// eslint-disable-next-line no-unused-vars
import { getreceivingAndIssuingLock, AddreceivingAndIssuingLock, startBlock, createOrUpdateReceivingLock, createOrUpdateIssuanceLock } from '@/api/materials/sendReceiveLock'
// eslint-disable-next-line no-unused-vars
import { debounce, advanceSearch, showLoading, hideLoading, selectDataClient, openAppClient, parseList, treeToList } from '@/utils/common'
import { mapMutations, mapState } from 'vuex'
import { getMaterialData, saveOrupdate, getOrgNameData, getlistPermissionOrg, deleteOrg } from '@/api/base/material'
export default {
    components: {
        Pagination,
        SelectOrg
    },
    computed: {
        ...mapState(['userInfo']),
        // 列表宽度
        rightTableWidth () {
            return (this.screenWidth - 300) + 'px'
        },
        // 列表高度
        rightTableHeight () {
            if (this.paginationInfo.total > 0) {
                return this.screenHeight - 170
            } else {
                return this.screenHeight - 118
            }
        },
        // 分配用户、分配岗位列表宽度
        rightTableWidth2 () {
            return (this.screenWidth - 300) + 'px'
        },
        rightTableHeight2 () {
            return this.screenHeight - 210
        },
        isCheck () {
            return (row, city)=>{
                const check = row.checkedCities.find(x=>x === city) ? true : false
                console.log('check', check)
                return check
            }
        }

    },
    data () {
        return {
            viewList: true, // 显示列表还是编辑界面: true 显示列表 false 显示编辑界面
            searchKey: '',
            treeData: [],
            goodsDataList: [],
            checkAll: false,
            checkedCities: [],
            citiess: ['query', 'addChildren', 'editChildren', 'delChildren', 'addDtl', 'editDtl', 'delDtl', 'use'],
            cities: ['查询', '添加子级', '编辑子级', '删除子级', '添加明细', '编辑明细', '删除明细', '使用'],
            isIndeterminate: false,
            currentRow: null,
            paginationInfo: {
                total: 0,
                pageSize: 10,
                currentPage: 1,
            },
            tableData: [],
            checkList: [],
            query: false,
            Add: false,
            Edit: false,
            Del: false,
            allData: [],
            radio: '2',
            formData: {
                'billId': '',
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'isAuthorize': null,
                'orgId': '',
                'orgName': '',
                'state': ''
            },
            currencyOptions: [],

            isUsing: '',
            options: [{
                value: '0',
                label: '停用'
            }, {
                value: '1',
                label: '启用'
            }],
            tabsName: 'baseInfo',
            tableData2: [],
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            idsTop: [],
            isclick: false, //是否点击
            selection: [],
            isShow: true,
            multipleSelection: [],
            p1: {}, //收料
            p2: {}, //发料
            queryparams: [],
            orgIds: '',
        }
    },
    created () {
        this.getTableData()
        //  this.getData()
    },
    mounted () {
        // 获取屏幕宽高
        this.getScreenInfo()
        window.addEventListener('resize', debounce(this.getScreenInfo))
    },

    methods: {
        ...mapMutations(['setSelectedInfo']),
        handleCheckAllChange (val) {
            const tree = this.goodsDataList
            treeToList(tree, item=>{
                if(val) {
                    this.$set(item, 'checkedCities', [...this.cities])
                }else{
                    this.$set(item, 'checkedCities', [])
                }
            })

        },
        //checkbox事件
        handleCheckedCitiesChange (value, row, isCheck) {
            console.log('row.checkedCities单独选择的值', row)
            this.queryparams.push(row)
            const tree = [row]
            treeToList(tree, item=>{
                if(item.billId !== row.billId) {
                    const index = item.checkedCities.findIndex(x=>x === value)
                    if(index === -1 && isCheck) {
                        item.checkedCities.push(value)
                    }else if(index !== -1 && !isCheck) {
                        item.checkedCities.splice(index, 1)
                    }
                }
            })
        },
        //每行的全选
        checkedAll (row) {
            console.log('row.checkedCities1111111全选的值', row)

            this.queryparams.push(row)
            this.$set(row, 'checkedCities', [...this.cities])
            const tree = [row]
            treeToList(tree, item=>{
                this.$set(item, 'checkedCities', [...this.cities])
            })
        },
        //取消全选
        cancelCheckedAll (row) {
            this.$set(row, 'checkedCities', [])
            const tree = [row]
            treeToList(tree, item=>{
                this.$set(item, 'checkedCities', [])
            })
        },
        //分配权限
        GoJurisdiction (formData) {
            if(this.isclick) {
                console.log('this.formData ', formData )
                this.orgId = this.formData.orgId
                this.orgName = this.formData.orgName
                this.isShow = false
                showLoading()
                this.getData()
            }else{
                this.clientPop('info', '请先选择组织机构！')
            }

        },
        //获取物资类别数据
        async getData () {
            const data =  await  getMaterialData()
            data.forEach(item=>{
                item.isCheck = true
                this.$set(item, 'checkedCities', [])
            })
            this.goodsDataList =  parseList(data, 'billId', 'parentClassId', '0')
            hideLoading()

        },

        startAndBlock (info) {
            startBlock(this.formData).then(()=>{
                this.clientPop('suc', info, ()=>{
                    this.getTableData()
                })
            })
        },

        //保存
        onSave () {
            //转一维数组
            this.queryparams.forEach(item=>{
                item.children.forEach(val=>{
                    this.queryparams.push(val)
                })
            })
            const obj1 = {
                dtls: [],
                'gmtModified': '',
                'modifierId': '',
                'modifierName': '',
                'orgId': this.orgId,
                'orgName': this.orgName

            }
            this.queryparams.forEach(item=>{
                const obj = {
                    'classId': item.billId,
                    'className': item.className,
                    'useCase': []
                }
                const obj2 = {
                    '查询': 'query',
                    '添加子级': 'addChildren',
                    '编辑子级': 'editChildren',
                    '删除子级': 'delChildren',
                    '添加明细': 'addDtl',
                    '编辑明细': 'editDtl',
                    '删除明细': 'delDtl',
                    '使用': 'use',
                }
                //转值
                function matchFn (arr, obj) {
                    return arr.map(v => obj[v])
                }
                const res = matchFn(item.checkedCities, obj2)
                obj.useCase = res
                //去重
                obj1.dtls.push(obj)
                let map = new Map()
                for (let item of obj1.dtls) {
                    if (!map.has(item.classId)) {
                        map.set(item.classId, item)
                    };
                };
                let arr = [...map.values()]
                obj1.dtls = arr
            })
            console.log('obj1', obj1)
            saveOrupdate(obj1).then(()=>{
                this.clientPop('suc', '操作成功!', ()=>{
                    this.getOrgName(this.orgId)
                })
            })

            // AddreceivingAndIssuingLock(this.formData).then(()=>{
            //     this.clientPop('suc', '保存成功!', ()=>{
            //         this.onCancel(),
            //         this.getTableData()
            //     })
            // })

        },
        //获取机构的物资类别权限
        getOrgName (orgId) {
            getOrgNameData({ 'orgId': orgId }).then(res=>{
                console.log('res>>>>', res)
            })
        },
        //删除
        ctDelete () {
            if(this.selection.length == 0) {
                this.clientPop('info', '请先选择要删除的数据!')
            }else{
                this.clientPop(
                    'info',
                    '确定删除当前选中的数据吗?',
                    this.delData
                )
            }
        },
        delData () {
            let arr = []
            this.selection.forEach(item=>{
                arr.push(item.orgId)
            })
            deleteOrg(arr).then(res => {
                if (res.code == 200) {
                    this.clientPop('suc', '删除成功', this.getTableData())
                }
            })
        },
        //获取选择项
        planTableSelect (selection) {
            this.selection = selection
        },

        handleCurrentChange (val) {
            this.formData = val
        },
        async getTableData () {
            showLoading()
            try {
                const resData = await getlistPermissionOrg({ orgId: this.orgIds })
                console.log('resData', resData.list)
                this.tableData = resData
                this.allData = JSON.parse(JSON.stringify(resData))
                this.paginationInfo.total = resData.totalCount
                this.viewList = true
                hideLoading()
            } catch (error) {
                hideLoading()
            }
        },
        async queryTableData () {
            const resData = this.allData.filter(item => {
                return item.userName.includes(this.searchKey)
            })
            this.tableData = resData
            this.paginationInfo.total = 0
        },
        //点击机构树的机构名称
        onSelectOrg (val) {
            console.log('1111111111', val)
            this.orgIds = val.orgId
            getlistPermissionOrg({ orgId: val.orgId })
            this.isclick = true
            this.formData = {
                ...val,
            }
            this.getTableData()
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        onSearch (e) {
            let searchKey = e
            if (typeof e === 'object') {
                searchKey = this.searchKey
            }
            console.log(searchKey)
            this.queryTableData()
        },
        onAdvanceSearch () {
            advanceSearch().then(res => {
                alert(JSON.stringify(res))
            })
        },
        goList () {
            this.viewList = true
        },

        // // 点击分配角色按钮
        // async onDistRole () {
        //     this.viewList = 'role'
        //     const data = await getRoleByOrg({
        //         orgId: this.currentRow.orgId,
        //         userId: this.currentRow.userId
        //     })
        //     this.tableData2 = data.filter(item => item.userId)
        // },
        // 选择角色
        // onSelectRole () {
        //     const SelectedIDs = this.tableData2.map(item => item.roleId)
        //     selectDataClient({
        //         SelectServiceToken: '/hr/role/getOrgRole', // 客户端对应方法名
        //         IsSingleMode: false, // 是否单选 true 单选 false 多选
        //         SelectedIDs, // 已选中id
        //         InitParamsStr: JSON.stringify({
        //             orgId: this.currentRow.orgId,
        //             userId: ''
        //         }),
        //         Title: '选择角色' // 标题
        //     }).then(val => {
        //         val.forEach(item => {
        //             console.log('item', item)
        //             // item.userId = this.currentRow.userId
        //             // item.userName = this.currentRow.userName
        //         })
        //         // 保存用户选择返回数据到store
        //         // this.setSelectedInfo(val)
        //         // openAppClient('/showSelectedData', '选择结果')
        //         this.tableData2 = val
        //     })
        // },
        // 保存分配角色
        // async onSave () {
        //     showLoading()
        //     try {
        //         await saveOrgRoleApi({
        //             url: {
        //                 orgId: this.currentRow.orgId,
        //                 userId: this.currentRow.userId,
        //             },
        //             params: this.tableData2
        //         })
        //         hideLoading()
        //         this.clientPop('suc', '保存成功', () => {
        //             this.getTableData()
        //         })
        //     } catch (error) {
        //         hideLoading()
        //     }
        //     this.viewList = true
        // },
        onDel (index) {
            this.tableData2.splice(index, 1)
        },
        onCancel () {
            this.isShow = true
        },
        getScreenInfo () {
            let screenWidth = document.documentElement.clientWidth || document.body.clientWidth
            let screenHeight = document.documentElement.clientHeight || document.body.clientHeight
            this.screenWidth = screenWidth
            this.screenHeight = screenHeight
        },
    }
}
</script>

<style lang="scss" scoped>
.el-form{
    padding-top: 25px;
}
::v-deep.is-indeterminate{
    margin-left: 10px;
}
::v-deep.el-checkbox__inner{
    margin-left: 10px;

}
::v-deep.el-checkbox__label{
    color: #909399
}
</style>
